import { useState } from "react";
import Navbar from "../../compoents/Navbar";
import { useNavigate } from "react-router-dom";
import style from "./index.module.css";
import { Stepper } from "antd-mobile";
import { Button } from "antd-mobile";
import { MailFill } from "antd-mobile-icons";
// 模拟药品数据
const mockMedicines = [
  {
    id: 1,
    name: "新冠预防中药 (正常人群) 1剂",
    price: 10.08,
    image: "/public/1103.jpg",
    description: "功效:主要提高免疫力,预防新冠疾病",
    category: "新冠预防中药",
    isPrescription: true,
    limit: 5,
    quantity: 0,
  },
  {
    id: 2,
    name: "新冠预防中药 (体弱人群) 1剂",
    price: 11.8,
    image: "/public/1203.jpg",
    description: "功效:主要提高免疫力,预防新冠疾病",
    category: "新冠预防中药",
    isPrescription: true,
    limit: 5,
    quantity: 0,
  },
  {
    id: 3,
    name: "新冠预防中药 (儿童人群) 1剂",
    price: 9.8,
    image: "/public/1303.jpg",
    description: "功效:主要提高免疫力,预防新冠疾病",
    category: "新冠预防中药",
    isPrescription: true,
    limit: null,
    quantity: 0,
  },
];

// 模拟检查项目数据
const mockExaminations = [
  {
    id: 1,
    name: "动态心电图",
    price: 150.00,
    category: "心电血压",
    hasNotes: true,
    selected: false,
  },
  {
    id: 2,
    name: "12导同步心电图检查",
    price: 30.00,
    category: "心电血压",
    hasNotes: false,
    selected: false,
  },
  {
    id: 3,
    name: "胸部X光片",
    price: 80.00,
    category: "放射普放",
    hasNotes: false,
    selected: false,
  },
  {
    id: 4,
    name: "腹部B超",
    price: 120.00,
    category: "超声检查",
    hasNotes: true,
    selected: false,
  },
  {
    id: 5,
    name: "心脏彩超",
    price: 200.00,
    category: "超声检查",
    hasNotes: false,
    selected: false,
  },
];

function Index() {
  const navigate = useNavigate();
  const [selectedCategory, setSelectedCategory] = useState("新冠预防中药");
  const [medicines, setMedicines] = useState(mockMedicines);
  const [examinations, setExaminations] = useState(mockExaminations);
  const [activeTab, setActiveTab] = useState("药品");

  const categories = [
    {
      key: "新冠预防中药",
      title: "新冠预防中药",
    },
    {
      key: "普通用药",
      title: "普通用药",
    },
    {
      key: "感冒用药",
      title: "感冒用药 (非处方)",
    },
  ];

  const examinationCategories = [
    {
      key: "心电血压",
      title: "心电血压",
    },
    {
      key: "放射普放",
      title: "放射普放",
    },
    {
      key: "超声检查",
      title: "超声检查",
    },
  ];

  // 计算已选商品数量和总价
  const selectedItems = medicines.filter((med) => med.quantity > 0);
  const selectedExaminations = examinations.filter((exam) => exam.selected);
  const totalItems = selectedItems.reduce((sum, med) => sum + med.quantity, 0) + selectedExaminations.length;
  const totalPrice = selectedItems.reduce(
    (sum, med) => sum + med.price * med.quantity,
    0
  ) + selectedExaminations.reduce((sum, exam) => sum + exam.price, 0);

  // 更新商品数量
  const updateQuantity = (id: number, quantity: number) => {
    setMedicines((prev) =>
      prev.map((med) =>
        med.id === id ? { ...med, quantity: Math.max(0, quantity) } : med
      )
    );
  };

  // 切换检查项目选择状态
  const toggleExamination = (id: number) => {
    setExaminations((prev) =>
      prev.map((exam) =>
        exam.id === id ? { ...exam, selected: !exam.selected } : exam
      )
    );
  };

  const goPay = (state:any) => {
    if (selectedItems.length === 0 && selectedExaminations.length === 0) {
      alert("请选择商品或检查项目");
      return;
    }
    // navigate('/OpenTrue')
    navigate('/OpenTrue',{state:mockMedicines})

    console.log("提交订单", { selectedItems, selectedExaminations });
  };

  return (
    <div className={style.container}>
      <Navbar title="开单申请" onBack={() => navigate(-1)} showBack />

      <div className={style.openBox}>
        {/* 自定义Tab头部 */}
        <div className={style.tabHeader}>
          <div className={style.tabContainer}>
            <div className={style.tabItem} onClick={() => setActiveTab("药品")}>
              <span className={`${style.tabText} ${activeTab === "药品" ? style.active : ""}`}>药品</span>
              {activeTab === "药品" && <div className={style.tabIndicator}></div>}
            </div>
            <div className={style.tabItem} onClick={() => {
              setActiveTab("检查");
              setSelectedCategory("心电血压");
            }}>
              <span className={`${style.tabText} ${activeTab === "检查" ? style.active : ""}`}>检查</span>
              {activeTab === "检查" && <div className={style.tabIndicator}></div>}
            </div>
            <div className={style.tabItem} onClick={() => setActiveTab("检验")}>
              <span className={`${style.tabText} ${activeTab === "检验" ? style.active : ""}`}>检验</span>
              {activeTab === "检验" && <div className={style.tabIndicator}></div>}
            </div>
          </div>
          <div className={style.orderRecordLink} onClick={() => navigate('/Order')}>
            <span>开单记录 {'>'}</span>
          </div>
        </div>
        <div className={style.tabDivider}></div>

        {/* 根据选中的tab显示内容 */}
        {activeTab === "药品" && (
          <div className={style.conpenBox}>
            <div className={style.sidebar}>
              {categories.map((item) => (
                <div
                  key={item.key}
                  className={`${style.sidebarItem} ${
                    selectedCategory === item.key ? style.active : ""
                  }`}
                  onClick={() => setSelectedCategory(item.key)}
                >
                  {item.title}
                </div>
              ))}
            </div>

            <div className={style.conpenBoxRight}>
              {medicines.map((medicine) => (
                <div key={medicine.id} className={style.medicineItem}>
                  <img src={medicine.image} alt={medicine.name} />

                  <div className={style.medicineImage}>
                    <div className={style.medicineInfo}>
                      <span className={style.medicineName}>
                        {medicine.name}
                      </span>
                      <p className={style.medicineDescription}>
                        {medicine.description}
                      </p>

                      <div className={style.medicineAction}>
                          <div className={style.price}>¥{medicine.price}</div>

                          <div className={style.medicineActions}>
                            <Stepper
                              value={medicine.quantity}
                              onChange={(value) =>
                                updateQuantity(medicine.id, value || 0)
                              }
                              min={0}
                              max={medicine.limit || 999}
                              className={style.stepper}
                            />
                          </div>
                      </div>
                    </div>

                    <div className={style.medicineTags}>
                      {medicine.isPrescription && (
                        <span
                          className={`${style.tag} ${style.prescription}`}
                        >
                          处方药
                        </span>
                      )}
                      {medicine.limit && (
                        <span className={`${style.tags} ${style.limit}`}>
                          限购{medicine.limit}剂
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {activeTab === "检查" && (
          <div className={style.conpenBox}>
            <div className={style.sidebar}>
              {examinationCategories.map((item) => (
                <div
                  key={item.key}
                  className={`${style.sidebarItem} ${
                    selectedCategory === item.key ? style.active : ""
                  }`}
                  onClick={() => setSelectedCategory(item.key)}
                >
                  {item.title}
                </div>
              ))}
            </div>

            <div className={style.conpenBoxRight}>
              {examinations
                .filter((exam) => exam.category === selectedCategory)
                .map((examination) => (
                  <div key={examination.id} className={style.examinationItem}>
                    <div className={style.examinationInfo}>
                      <div className={style.examinationName}>
                        {examination.name}
                      </div>
                      <div className={style.examinationPrice}>
                        ¥{examination.price.toFixed(2)}/次
                      </div>
                      {examination.hasNotes && (
                        <div className={style.notesTag}>注意事项</div>
                      )}
                    </div>
                    <div 
                      className={`${style.selectButton} ${examination.selected ? style.selected : ''}`}
                      onClick={() => toggleExamination(examination.id)}
                    >
                      {examination.selected && <span className={style.checkmark}>✓</span>}
                    </div>
                  </div>
                ))}
            </div>
          </div>
        )}

        {activeTab === "检验" && (
          <div className={style.emptyContent}>
            <p>检验功能开发中...</p>
          </div>
        )}

        <div className={style.openOrder}>
          <div className={style.openOrderLeft}>


            <div className={style.orderIcon}>
               <MailFill fontSize={20} className={style.mailIcon}/>
            </div>


            <div className={style.openOrderLeftRight}>
              <span className={style.selectedCount}>
                已选 <span className={style.countNumber}>{totalItems}</span> 项
              </span>
              <span className={style.totalPrice}>
                合计: {" "}
                <span className={style.priceNumber}>
                ¥{totalPrice.toFixed(2)}
                </span>
              </span>
            </div>


          </div>

          <Button
            className={style.submitButton}
            onClick={()=>goPay(mockMedicines)}
            disabled={totalItems === 0}
          >
            提交
          </Button>
        </div>
      </div>
    </div>
  );
}

export default Index;
